package com.i2bt.app.files.model;

import com.i2bt.common.AndroidRestContract;

import com.i2bt.app.BaseActivity;
import com.i2bt.app.BaseJsonModel;
import com.i2bt.app.files.FilesUploadActivity;
import com.i2bt.bean.FileBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class FilesUploadJsonHandle extends BaseJsonModel {

	public FilesUploadJsonHandle(BaseActivity activity) {
		super(activity);
	}

protected String logicToWrap() throws JSONException {
		
		switch (beanParam.getAct()) {

		// 获取资源目录
		case AndroidRestContract.UPLOAD_FILES : {
			jsonStrParam = wrapUploadFiles();
			break;
		}

		}
		
		return jsonStrParam;
	}
	
	/**
	 * 把获取目录的bean打包成json
	 * @return 打包后的json
	 * @throws JSONException
	 */
	private String wrapUploadFiles() throws JSONException {
		
		wrapCommonJson();
		
		FileBean fileBean = (FileBean) beanParam;
		try {
			jsonParam.put(AndroidRestContract.PARENT_PATH, 
					URLEncoder.encode(fileBean.getParentPath(), "utf-8"))
			.put("MD5", fileBean.getMD5())
			.put("fileSize", fileBean.getFileSize())
			.put("fileNames", strsToJsonArray(fileBean.getUploadFiles()));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return jsonParam.toString();
	}
	
	@Override
	protected void logicToUnwrap(boolean isSuc, String result)
			throws JSONException {
		
		if (isSuc) {
			
			jsonParam = new JSONObject(result);

			if (jsonParam.getBoolean(AndroidRestContract.SUCCEED)) {
				FilesUploadActivity filesUploadActivity = (FilesUploadActivity)activity;

				switch (jsonParam.getInt(AndroidRestContract.ACTION)) {
				
				// 移动文件
				case AndroidRestContract.UPLOAD_FILES : {
					String ip = jsonParam.getString("ip");
					int port = jsonParam.getInt("port");
//					filesUploadActivity.filesUploadResponse(ip, port);
					break;
				}

				}
			}
			else {
				activity.toastHandler(jsonParam.
						getString(AndroidRestContract.MESSAGE));
			}
		}
		else {
			activity.toastHandler(result);
		}
	}
	
	

}
